import { useState } from 'react';
import { usePersistFn } from 'ahooks';
import { useWebsocketPush } from '@/common/hooks';

const useMessageState = ({ pushDanmaku, destroyPlayer }) => {
  const [onlineCount] = useState(0);
  const [message, setMessage] = useState([]);

  // 添加消息
  const addMessage = usePersistFn((msg) => setMessage(message.concat(msg)));

  // 普通消息
  const simpleMessageHandle = usePersistFn((m, isHistory = false) => {
    // 添加到消息列表
    addMessage(m);
    // 发送弹幕
    if (pushDanmaku && !isHistory) pushDanmaku(m);
  });

  // 机器人消息
  const robotMessageHandle = addMessage;

  // 消息回调
  const socketMessageHandle = usePersistFn((m) => {
    let res;
    try {
      res = JSON.parse(m);
    } catch {
      res = {};
    }
    const { codeType, data: text = '{}' } = res;
    let contain;
    try {
      contain = JSON.parse(text);
    } catch {
      contain = {};
    }

    // 错误信息
    // if (errorCode !== 0 || codeType === 100022) return errorMessageHandle(contain);
    // 普通发言消息
    if (codeType === 100004) {
      const obj = {
        messageType: codeType,
        username: contain.fromusername,
        message: contain.textMessage,
        roomId: contain.roomId,
      };
      return simpleMessageHandle(obj);
    }
    // 历史消息
    if (codeType === 100005) {
      if (!Array.isArray.call(window, contain)) return;
      contain.forEach((item) => {
        try {
          const { roomId, levelId: level, fromusername: username, textMessage } = JSON.parse(item);
          const obj = {
            roomId,
            messageType: codeType,
            username,
            message: textMessage,
            level,
          };
          return simpleMessageHandle(obj, true);
        } catch (e) {
          // eslint-disable-next-line
          console.error(e);
        }
      });
    }
    // 欢迎进入直播间
    if (codeType === 100006) {
      const obj = {
        messageType: codeType,
        username: contain.fromusername,
        message: contain.textMessage,
        level: contain.levelId,
      };
      return simpleMessageHandle(obj);
    }
    // 系统广播
    if (codeType === 100021) {
      const obj = {
        messageType: codeType,
        message: contain.textMessage,
        level: contain.levelId,
      };
      return simpleMessageHandle(obj);
    }
    // 机器人消息
    if (codeType === 6) return robotMessageHandle(contain);
    // 下播消息
    if (codeType === 7) return destroyPlayer();
    // 礼物消息
    // if (codeType === 2) return giftMessageHandle(m);
    // 预测购买消息
    // if (codeType === 9) return forecastPurchaseMessageHandle(m);
    // 抢红包消息
    // if (codeType === 13) return addMessage(m);
    // 发红包消息
    // if (codeType === 12) return sendRedPackMessageHandle(m);
  });

  // 连接websocket
  const path = `/websocket/youke_${new Date().getTime()}`;
  const socket = useWebsocketPush(
    path,
    socketMessageHandle,
  );

  // 发送消息
  const sendMessageHandle = usePersistFn((msg) => {
    const msgString = JSON.stringify(msg);
    if (socket) {
      socket.sendHandle(msgString);
    } else {
      window.messageList = window.messageList || [];
      window.messageList.push(msgString);
    }
  });

  return {
    socket,
    onlineCount,
    message,
    setMessage,
    sendMessage: sendMessageHandle,
  };
};

export default useMessageState;
